//
//  ZXChatBoxView.m
//  ZXDNLLTest
//
//  Created by mxsm on 16/5/19.
//  Copyright © 2016年 mxsm. All rights reserved.
//

#import "ZXChatBoxView.h"

#define     CHATBOX_BUTTON_WIDTH        37
#define     HEIGHT_TEXTVIEW             HEIGHT_TABBAR * 0.74
#define     MAX_TEXTVIEW_HEIGHT         104

@interface ZXChatBoxView ()<UITextViewDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (nonatomic, strong) UIView *topLine; // 顶部的线
@property (nonatomic, strong) UIButton *picButton; // 声音按钮
@property (nonatomic, strong) UITextView *textView;  // 输入框
@property (nonatomic, strong) UIButton *faceButton;  // 表情按钮
@property (nonatomic, strong) UIButton *sendBtn;

@end

@implementation ZXChatBoxView

-(id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        _curHeight = frame.size.height;// 当前高度初始化为 49
        [self setBackgroundColor:DEFAULTBGCOLOR];
        [self addSubview:self.topLine];
        [self addSubview:self.picButton];
        [self addSubview:self.textView];
        [self addSubview:self.faceButton];
        [self addSubview:self.sendBtn];
        self.status = TLChatBoxStatusNothing;//初始化状态是空
    }
    
    return self;
    
}


-(void)setFrame:(CGRect)frame
{
    // 6 的初始化 0.0.375.49
    [super setFrame:frame];
    [self.topLine setFrameWidth:self.frameWidth];
    //  y=  49 -  ( CHATBOX_BUTTON_WIDTH )  37 - (View 的H - Button的H )/2
    //  Voice 的高度和宽度初始化的时候都是 37 
    float y = self.frameHeight - self.picButton.frameHeight - (HEIGHT_TABBAR - CHATBOX_BUTTON_WIDTH) / 2;
    if (self.picButton.originY != y) {
        [UIView animateWithDuration:0.1 animations:^{
            // 根据 Voice 的 Y 改变 faceButton  moreButton de Y
            [self.picButton setOriginY:y];
            [self.faceButton  setOriginY:self.picButton.originY];
        }];
    }
}


#pragma mark -- 拉黑
- (void)black{
    self.backgroundColor=[UIColor whiteColor];
    self.textView.backgroundColor=DEFAULTBGCOLOR;
    self.textView.textAlignment=NSTextAlignmentCenter;
    self.textView.text=@"你已被管理员禁言";
    self.textView.layer.borderWidth=0.0;
    self.textView.textColor=DEFAULTTEXTGRAYCOLOR;
}


- (void)hiddenSendBtn{
    self.sendBtn.hidden=YES;
    CGRect frame= _textView.frame;
    frame.size.width=SCREEN_WIDTH-CHATBOX_BUTTON_WIDTH*2-15;
    [_textView setFrame:frame];
}

#pragma Public Methods
- (BOOL) resignFirstResponder
{
    
    [self.textView resignFirstResponder];
    [_faceButton setImage:[UIImage imageNamed:@"ToolViewEmotion"] forState:UIControlStateNormal];
    [self hiddenSendBtn];
    return [super resignFirstResponder];
    
}

- (void) addEmojiFace:(ChatFace *)face
{
    
    [self.textView setText:[self.textView.text stringByAppendingString:[NSString stringWithFormat:@"%@",face.faceName]]];
    if (MAX_TEXTVIEW_HEIGHT < self.textView.contentSize.height) {
        float y = self.textView.contentSize.height - self.textView.frameHeight;
        y = y < 0 ? 0 : y;
        [self.textView scrollRectToVisible:CGRectMake(0, y, self.textView.frameWidth, self.textView.frameHeight) animated:YES];
    }
    
    [self textViewDidChange:self.textView];
    
}

/**
 *  发送当前消息
 */

- (void) sendCurrentMessage
{
    if (self.textView.text.length > 0) {     // send Text
        if (_delegate && [_delegate respondsToSelector:@selector(chatBox:sendTextMessage:)]) {
            [_delegate chatBox:self sendTextMessage:self.textView.text];
        }
    }
    [self.textView setText:@""];
    [self textViewDidChange:self.textView];
}


- (void) deleteButtonDown
{
    [self textView:self.textView shouldChangeTextInRange:NSMakeRange(self.textView.text.length - 1, 1) replacementText:@""];
    [self textViewDidChange:self.textView];
}


#pragma mark - UITextViewDelegate
- (void) textViewDidBeginEditing:(UITextView *)textView
{
    /**
     *   textView 已经开始编辑的时候，判断状态
     */
    [self hiddenSendBtn];
    ZXChatBoxStatus lastStatus = self.status;
    self.status = TLChatBoxStatusShowKeyboard;
    if (lastStatus == TLChatBoxStatusShowFace) {
        
        [_faceButton setImage:[UIImage imageNamed:@"ToolViewEmotion"] forState:UIControlStateNormal];
        
    }if (_delegate && [_delegate respondsToSelector:@selector(chatBox:changeStatusForm:to:)]) {
        
        [_delegate chatBox:self changeStatusForm:lastStatus to:self.status];
    }
}

/**
 *  TextView 的输入内容一改变就调用这个方法，
 *
 *  
 */
- (void) textViewDidChange:(UITextView *)textView
{
    /**
     *   textView 的 Frame 值是按照 talkButton  设置的
         sizeThatSize并没有改变原始 textView 的大小
         [label sizeToFit]; 这样搞就直接改变了这个label的宽和高，使它根据上面字符串的大小做合适的改变
     */
    CGFloat height = [textView sizeThatFits:CGSizeMake(self.textView.frameWidth, MAXFLOAT)].height;
    height = height > HEIGHT_TEXTVIEW ? height : HEIGHT_TEXTVIEW; // height大于 TextView 的高度 就取height 否则就取 TextView 的高度
    
    height = height < MAX_TEXTVIEW_HEIGHT ? height : textView.frameHeight;  // height 小于 textView 的最大高度 104 就取出 height 不然就取出  textView.frameHeight
    
    _curHeight = height + HEIGHT_TABBAR - HEIGHT_TEXTVIEW;
    if (_curHeight != self.frameHeight) {
       
        [UIView animateWithDuration:0.05 animations:^{
            [self setFrameHeight:_curHeight];
            if (_delegate && [_delegate respondsToSelector:@selector(chatBox:changeChatBoxHeight:)]) {
                
                [_delegate chatBox:self changeChatBoxHeight:_curHeight];
                
            }
        }];
    }
    
    if (height != textView.frameHeight) {
        
        [UIView animateWithDuration:0.05 animations:^{
            
            [textView setFrameHeight:height];
            
        }];
    }
}

////内容将要发生改变编辑
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    
    if ([text isEqualToString:@"\n"]){
        [self sendCurrentMessage];
        return NO;
    }
    /**
     *
     */
    else if (textView.text.length > 0 && [text isEqualToString:@""]) {       // delete
        
        if ([textView.text characterAtIndex:range.location] == ']') {
            
            NSUInteger location = range.location;
            NSUInteger length = range.length;
            while (location != 0) {
                location --;
                length ++ ;
                char c = [textView.text characterAtIndex:location];
                if (c == '[') {
                    
                    textView.text = [textView.text stringByReplacingCharactersInRange:NSMakeRange(location, length) withString:@""];
                    return NO;
                    
                }
                else if (c == ']') {
                    
                    return YES;
                }
            }
        }
    }
    
    return YES;
}


#pragma mark - Event Response
/**
 *  图片点击
 *
 */
- (void)picButtonDown:(UIButton *)sender
{
    ZXChatBoxStatus lastStatus = self.status;
    // 显示talkButton
    self.curHeight = HEIGHT_TABBAR;
    [self setFrameHeight:self.curHeight];
    self.status = TLChatBoxStatusShowVoice;
    [self.textView resignFirstResponder];
    if (lastStatus == TLChatBoxStatusShowFace) {
        [_faceButton setImage:[UIImage imageNamed:@"ToolViewEmotion"] forState:UIControlStateNormal];
    }
    if (_delegate && [_delegate respondsToSelector:@selector(chatBox:changeStatusForm:to:)]) {
        [_delegate chatBox:self changeStatusForm:lastStatus to:self.status];
    }
    UIViewController *vc=[TGTools viewController:self];
    
    UIAlertController *alertCtrl=[UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancleAction=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];;
    UIAlertAction *albumAction=[UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        UIImagePickerController * ipc = [[UIImagePickerController alloc] init];
        ipc.delegate = self;
        ipc.sourceType = sourceType;
        [vc presentViewController:ipc animated:YES completion:nil];
    }];
    UIAlertAction *cameraAction=[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        UIImagePickerController * ipc = [[UIImagePickerController alloc] init];
        ipc.delegate = self;
        ipc.sourceType = sourceType;
        [vc presentViewController:ipc animated:YES completion:nil];
    }];
    [alertCtrl addAction:cancleAction];
    [alertCtrl addAction:albumAction];
    [alertCtrl addAction:cameraAction];
    [vc presentViewController:alertCtrl animated:YES completion:nil];
    
}


#pragma mark -- UINavigationControllerDelegate, UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    if (_delegate && [_delegate respondsToSelector:@selector(chatBox:sendPictureMessage:)]) {
        [_delegate chatBox:self sendPictureMessage:image];
    }
    [[TGTools viewController:self] dismissViewControllerAnimated:YES completion:nil];
}

/**
 *  表情按钮点击时间
 *
 */
- (void) faceButtonDown:(UIButton *)sender
{
    ZXChatBoxStatus lastStatus = self.status;// 记录下上次的状态
    if (lastStatus == TLChatBoxStatusShowFace) {
        // 正在显示表情，改为现实键盘状态
        self.status = TLChatBoxStatusShowKeyboard;
        [_faceButton setImage:[UIImage imageNamed:@"ToolViewEmotion"] forState:UIControlStateNormal];
        [self.textView becomeFirstResponder];
        [self hiddenSendBtn];
        
        
        
        if (_delegate && [_delegate respondsToSelector:@selector(chatBox:changeStatusForm:to:)]) {
            [_delegate chatBox:self changeStatusForm:lastStatus to:self.status];
        }
    }else{
        self.status = TLChatBoxStatusShowFace;
        [_faceButton setImage:[UIImage imageNamed:@"ToolViewKeyboard"] forState:UIControlStateNormal];
        if (lastStatus == TLChatBoxStatusShowVoice) {
            [_picButton setImage:[UIImage imageNamed:@"pic"] forState:UIControlStateNormal];
            [_textView setHidden:NO];
            [self textViewDidChange:self.textView];
        }else if (lastStatus == TLChatBoxStatusShowKeyboard) {
            [self.textView resignFirstResponder];
        }
        
        self.sendBtn.hidden=NO;
        CGRect frame= _textView.frame;
        frame.size.width=SCREEN_WIDTH-CHATBOX_BUTTON_WIDTH*2-75;
        [_textView setFrame:frame];
        if (_delegate && [_delegate respondsToSelector:@selector(chatBox:changeStatusForm:to:)]) {
            [_delegate chatBox:self changeStatusForm:lastStatus to:self.status];
        }
    }
}

#pragma mark - Getter
- (UIView *) topLine
{
    if (_topLine == nil) {
        _topLine = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.5)];
        [_topLine setBackgroundColor:RGB_COLOR(165, 165, 165)];
    }
    return _topLine;
}

- (UIButton *) picButton
{
    if (_picButton == nil) {
        _picButton = [[UIButton alloc] initWithFrame:CGRectMake(CHATBOX_BUTTON_WIDTH, (HEIGHT_TABBAR - CHATBOX_BUTTON_WIDTH) / 2, CHATBOX_BUTTON_WIDTH, CHATBOX_BUTTON_WIDTH)];
        [_picButton setImage:[UIImage imageNamed:@"pic"] forState:UIControlStateNormal];
        [_picButton addTarget:self action:@selector(picButtonDown:) forControlEvents:UIControlEventTouchUpInside];
    
    }
    return _picButton;
}

- (UITextView *) textView
{
    if (_textView == nil) {
        _textView = [[UITextView alloc] initWithFrame:CGRectMake(CHATBOX_BUTTON_WIDTH*2, self.frameHeight * 0.13, SCREEN_WIDTH-CHATBOX_BUTTON_WIDTH*2-15, HEIGHT_TEXTVIEW)];
        [_textView setFont:[UIFont systemFontOfSize:16.0f]];
        [_textView.layer setMasksToBounds:YES];
        [_textView.layer setCornerRadius:4.0f];
        [_textView.layer setBorderWidth:0.5f];
        [_textView.layer setBorderColor:self.topLine.backgroundColor.CGColor];
        [_textView setScrollsToTop:NO];
        [_textView setReturnKeyType:UIReturnKeySend];// 返回按钮更改为发送
        [_textView setDelegate:self];
    }
    return _textView;
}

- (UIButton *) faceButton{
    if (_faceButton == nil) {
        _faceButton = [[UIButton alloc] initWithFrame:CGRectMake(0, (HEIGHT_TABBAR - CHATBOX_BUTTON_WIDTH) / 2, CHATBOX_BUTTON_WIDTH, CHATBOX_BUTTON_WIDTH)];
        [_faceButton setImage:[UIImage imageNamed:@"ToolViewEmotion"] forState:UIControlStateNormal];
        [_faceButton addTarget:self action:@selector(faceButtonDown:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _faceButton;
}

- (UIButton *)sendBtn{
    if (_sendBtn == nil) {
        _sendBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-60, (HEIGHT_TABBAR - CHATBOX_BUTTON_WIDTH) / 2+3, 50, 30)];
        [_sendBtn setTitle:@"发送" forState:UIControlStateNormal];
        _sendBtn.backgroundColor=NAVCOLOR;
        [_sendBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _sendBtn.layer.masksToBounds=YES;
        _sendBtn.layer.cornerRadius=3.0;
        _sendBtn.hidden=YES;
        [_sendBtn addTarget:self action:@selector(sendCurrentMessage) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sendBtn;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
